package com.superquan.selfstudybootmybatis.utils.saxparse;
import com.superquan.selfstudybootmybatis.entity.user.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


/**
 * @author zwq
 * @description sax方式解析xml文件
 * @date 2022/7/12
 */
@Slf4j
public class XmlParseHandler extends DefaultHandler {
    String value = null;//xml属性值
    String curProperty = null;//xml属性名
    private User user;

    /**
     * 用来标识解析开始
     */
    @Override
    public void startDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.startDocument();
        log.info("------###### xml文件解析开始");
    }


    /**
     * 用来标识解析结束
     */
    @Override
    public void endDocument() throws SAXException {
        // TODO Auto-generated method stub
        super.endDocument();
        log.info("------###### xml文件解析结束");
    }


    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) throws SAXException {
        //调用DefaultHandler类的startElement方法
        super.startElement(uri, localName, qName, attributes);
        //获取xml名
        curProperty = qName.toLowerCase();
        log.info("------###### startElement qName :" + qName + " | localName:" + localName + " | uri:" +uri);
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        //调用DefaultHandler类的endElement方法
        super.endElement(uri, localName, qName);
        log.info("------###### endElement qName :" + qName + " | localName:" + localName + " | uri:" +uri);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException{
        super.characters(ch, start, length);
        // 将当前TextNode转换为String（xml属性值）
        value = new String(ch, start, length);
        log.info("------###### characters xml属性值:"+value);
        log.info("------###### 节点值是：" + curProperty + ":"+ value);
        if(curProperty.equalsIgnoreCase("ID")){
            user.setId(Integer.valueOf(value));
        }else if(curProperty.equalsIgnoreCase("USERNAME")){
            user.setUserName(value);
        }else if(curProperty.equalsIgnoreCase("PASSWORD")){
            user.setPassword(value);
        }else if(curProperty.equalsIgnoreCase("REALNAME")){
            user.setRealName(value);
        }
    }

    public void getUserInfo(){
        System.out.println(user.toString());
    }
}
